<template>
  <div class="app-container">
    <!-- 登录状态检查 -->
    <el-alert
      v-if="!isLoggedIn"
      title="请先登录微信公众号"
      type="warning"
      show-icon
      :closable="false"
      style="margin-bottom: 20px;"
    />

    <!-- 登录对话框 -->
    <el-dialog
      title="微信公众号管理员登录"
      :visible.sync="loginDialogVisible"
      width="350px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="qrcode-container" v-loading="qrcodeLoading">
        <img v-if="qrcodeUrl" :src="'data:image/png;base64,' + qrcodeUrl" class="qrcode-image" />
        <div v-else class="qrcode-placeholder">
          <el-button type="primary" @click="getLoginQrcode">获取登录二维码</el-button>
        </div>
      </div>
      <div class="login-status" v-if="qrcodeUrl">
        {{ loginStatusText }}
      </div>
    </el-dialog>

    <!-- 主要内容 -->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="类型" prop="log_type">
        <el-radio v-model="queryParams.log_type" label="微信公众号" @click="queryParams.log_type = '微信公众号'">微信公众号</el-radio>
        <el-radio v-model="queryParams.log_type" label="网页" @click="queryParams.log_type = '网页'">网页</el-radio>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirmRelogin">微信公众号，重新登录</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="list" style="width: 100%;">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column v-if="queryParams.log_type === '微信公众号'" label="公众号数量" align="center" prop="official_count" />
      <el-table-column v-if="queryParams.log_type === '微信公众号'" label="文章数量" align="center" prop="articles_count" />

      <el-table-column v-if="queryParams.log_type==='网页'" label="新闻数量" align="center" prop="news_count" />
      <el-table-column v-if="queryParams.log_type==='网页'" label="新闻JSON" show-overflow-tooltip align="center" prop="news_json" :formatter="newsJsonFormatter" />

      <el-table-column v-if="queryParams.log_type==='网页'" label="时间" align="center" prop="created_at" />
      <el-table-column v-else label="日期" align="center" prop="created_at_date" />
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="getList" />
  </div>

</template>
<style>
.el-input__inner {
  width: 90%;
}
.el-input__suffix {
  right: 10%;
}
.qrcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}
.qrcode-image {
  max-width: 200px;
  max-height: 200px;
}
.qrcode-placeholder {
  text-align: center;
}
.login-status {
  text-align: center;
  margin-top: 15px;
  color: #606266;
}
</style>
<script>
import { officialLogList, checkWeixinLoginStatus, getWeixinLoginQrcode, checkWeixinScanStatus } from '@/api/basics'
export default {
  name: 'Index',
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        log_type: '微信公众号'
      },
      // 登录相关
      isLoggedIn: false,
      loginDialogVisible: false,
      qrcodeLoading: false,
      qrcodeUrl: '',
      loginStatusText: '请扫描二维码登录',
      checkLoginTimer: null
    }
  },
  watch: {
    queryParams: {
      handler(val) {
        this.getList()
      },
      deep: true // 深度监听
      // immediate: true // 初次监听即执行
    }
  },
  created() {
    this.checkLoginStatus()
  },
  beforeDestroy() {
    if (this.checkLoginTimer) {
      clearTimeout(this.checkLoginTimer)
    }
  },
  methods: {
    newsJsonFormatter(row) {
      return JSON.stringify(row.news_json)
    },
    async checkLoginStatus() {
      try {
        this.loading = true
        const res = await checkWeixinLoginStatus()
        if (res.code === 10000) {
          this.isLoggedIn = res.data.is_logged_in
          if (!this.isLoggedIn) {
            this.loginDialogVisible = true
            this.getLoginQrcode() // 自动获取二维码
          }
        } else {
          this.$message.error(res.msg || '检查登录状态失败')
        }
        this.getList()
      } catch (error) {
        this.$message.error('检查登录状态失败')
      } finally {
        this.loading = false
      }
    },
    async getLoginQrcode() {
      this.qrcodeLoading = true
      try {
        const res = await getWeixinLoginQrcode()
        if (res.code === 10000) {
          this.qrcodeUrl = res.data.qr_code
          this.startCheckingLoginStatus()
        } else {
          this.$message.error(res.msg || '获取二维码失败')
        }
      } catch (error) {
        this.$message.error('获取二维码失败')
      } finally {
        this.qrcodeLoading = false
      }
    },
    startCheckingLoginStatus() {
      if (this.checkLoginTimer) {
        clearTimeout(this.checkLoginTimer)
      }

      this.loginStatusText = '请扫描二维码登录'
      this.checkLoginStatus_recursive()
    },
    async checkLoginStatus_recursive() {
      if (!this.loginDialogVisible) {
        return // 如果对话框已关闭，停止轮询
      }

      try {
        const res = await checkWeixinScanStatus()
        if (res.code === 10000) { // 登录成功
          this.isLoggedIn = true
          this.loginDialogVisible = false
          this.$message.success('登录成功')
          this.getList()
        } else {
          // 其他状态继续轮询，显示提示消息
          this.loginStatusText = res.msg || '等待扫码或确认中'
          // 等待1秒后再次检查
          this.checkLoginTimer = setTimeout(() => {
            this.checkLoginStatus_recursive()
          }, 1000)
        }
      } catch (error) {
        // 发生错误时继续轮询，只显示错误消息
        this.loginStatusText = '检查登录状态失败，继续等待中...'
        console.error('检查登录状态失败:', error)
        // 等待1秒后再次检查
        this.checkLoginTimer = setTimeout(() => {
          this.checkLoginStatus_recursive()
        }, 1000)
      }
    },
    confirmRelogin() {
      this.$confirm('重新登录可能会影响当前的服务，是否继续，不清楚的请勿操作？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleRelogin()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消重新登录'
        })
      })
    },
    handleRelogin() {
      this.isLoggedIn = false
      this.qrcodeUrl = ''
      this.loginStatusText = '请扫描二维码登录'
      this.loginDialogVisible = true
      this.getLoginQrcode()
    },
    /** 查询清单列表 */
    getList() {
      this.loading = true
      officialLogList(this.queryParams).then(response => {
        this.list = response.data
        this.total = response.count
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        page: 1,
        limit: 10,
        brand_name: undefined
      }
      this.handleQuery()
    }
  }
}
</script>

